package com.aboo.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Yata Aboo
 * @Date 2012-9-17
 * @Desc session工具包
 */
public class SessionUtil {

	/**
	 * 从session中获取attribute参数，取值为String类型
	 * @param request HttpServletRequest
	 * @param key 参数键名称
	 * @param defaultValue 如果为空时，取的默认值
	 * @return 参数值
	 */
	public static String getStringDefault(HttpServletRequest request, String key, String defaultValue) {
		HttpSession session = request.getSession();
		if (session.getAttribute(key) == null) {
			return defaultValue;
		}
		return (String) session.getAttribute(key);
	}
	
	/**
	 * 从session中获取attribute参数，取值为String类型
	 * @param request HttpServletRequest
	 * @param key 参数键名称
	 * @return 参数值
	 */
	public static String getString(HttpServletRequest request, String key) {
		HttpSession session = request.getSession();
		return (String) session.getAttribute(key);
	}
	
	/**
	 * 从session中获取attribute参数，取值为Integer类型
	 * @param request HttpServletRequest
	 * @param key 参数键名称
	 * @param defaultValue 如果为空时，取的默认值
	 * @return 参数值
	 */
	public static Integer getIntegerDefault(HttpServletRequest request, String key, Integer defaultValue) {
		HttpSession session = request.getSession();
		if (session.getAttribute(key) == null) {
			return defaultValue;
		}
		return (Integer) session.getAttribute(key);
	}
	
	/**
	 * 从session中获取attribute参数，取值为Integer类型
	 * @param request HttpServletRequest
	 * @param key 参数键名称
	 * @return 参数值
	 */
	public static Integer getInteger(HttpServletRequest request, String key) {
		return getIntegerDefault(request, key, null);
	}
	
	/**
	 * 从session中获取attribute参数，取值为Object类型
	 * @param request HttpServletRequest
	 * @param key
	 * @return 值
	 */
	public static Object getObject(HttpServletRequest request, String key) {
		HttpSession session = request.getSession();
		return session.getAttribute(key);
	}
	
	/**
	 * 向session的attribute中插入值
	 * @param request HttpServletRequest
	 * @param key 参数键名称
	 * @param value 参数值
	 */
	public static void setAttribute(HttpServletRequest request, String key, Object value) {
		HttpSession session = request.getSession();
		session.setAttribute(key, value);
	}	
	
	/**
	 * 移除session中值
	 * @param request HttpServletRequest
	 * @param key 参数键名称
	 */
	public static void removeAttribute(HttpServletRequest request, String key) {
		HttpSession session = request.getSession();
		session.removeAttribute(key);
	}
	
	/**
	 * 将session值为过期
	 * @param request HttpServletRequest
	 */
	public static void invalidate(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.invalidate();
	}
}
